# encoding: utf-8
# @File  : task.py
# @Author: shaoyun
# @Date  : 2025/05/11

from datetime import datetime
from typing import Dict, List, Optional, Any

from pydantic import BaseModel, Field, field_validator, ConfigDict

from app.models.task import TaskStatus


class TaskBase(BaseModel):
    """任务基本信息"""
    name: str
    spider_id: str
    parameters: Optional[Dict[str, Any]] = Field(default_factory=dict)
    priority: int = 0
    cron: Optional[str] = None


class TaskCreate(TaskBase):
    """创建任务的请求模型"""
    pass


class TaskUpdate(BaseModel):
    """更新任务的请求模型"""
    name: Optional[str] = None
    parameters: Optional[Dict[str, Any]] = None
    priority: Optional[int] = None
    cron: Optional[str] = None
    status: Optional[str] = None

    @field_validator('status')
    @classmethod
    def validate_status(cls, v):
        if v and v not in [status.value for status in TaskStatus]:
            raise ValueError(f"Invalid status value: {v}")
        return v


class TaskInDB(TaskBase):
    """数据库中的任务模型"""
    id: str
    user_id: str
    status: str
    created_at: datetime
    updated_at: datetime
    started_at: Optional[datetime] = None
    finished_at: Optional[datetime] = None

    model_config = ConfigDict(from_attributes=True)


class TaskWithResults(TaskInDB):
    """包含结果的任务模型"""
    results: Optional[List[Dict[str, Any]]] = None


class TaskScheduleInfo(BaseModel):
    """任务调度信息"""
    task_id: str
    node_id: str
    assigned_at: datetime


class TaskDetail(TaskInDB):
    """任务详细信息（包含额外的统计信息）"""
    retry_count: int = 0
    error_message: Optional[str] = None
    result_count: int = 0
    duration: Optional[float] = None
    spider_name: Optional[str] = None
    node_name: Optional[str] = None